"use strict";
import Vue from 'vue';
import axios from "axios";
import store from '@/store'
import router from "@/router";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 偷懒，因为开发环境中这个选项是true
let isDebug = Vue.config.devtools

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  baseURL: isDebug ? "http://localhost:8080" : ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

// 简单封装，目的是拦截token

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // 获取存储在vuex的token
    // 第一次登录时，token应该是不存在的，null或者空串
    if (!store.getters.getToken) {
      config.headers['token'] = window.sessionStorage.getItem("token")
    }else{
      config.headers['token'] = store.getters.getToken
    }
    console.log(config)
    return config;
  },
  function (error) {
    // Do something with request error
    // 输出错误
    console.log(error)
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    let res = response.data;
    console.log(res)
    // 判断是否请求成功
    if (res.code === 200) {
      return response
    } else {
      return Promise.reject(response.data.msg)
    }
  },
  function (error) {
    // Do something with response error
    console.log(error)
    if (error.response.data) {
      error.message = error.response.data.msg
    }
    // 401 -- 未授权
    if (error.response.status === 401) {
      router.push("/login")
    }
    return Promise.reject(error);
  }
);

// eslint-disable-next-line no-unused-vars
Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
